//
//  MovieDetailViewController.m
//  product_B
//
//  Created by lanou on 16/5/30.
//  Copyright © 2016年 lanou. All rights reserved.
//

#import "MovieDetailViewController.h"
#import "MovieHeadView.h"
#import "MovieDetailModel.h"
#import "MovieStoryModel.h"
#import "MovieCommentModel.h"
#import "MovieStoryTableViewCell.h"
#import "MovieTableTableViewCell.h"
#import "MovieCommentTableViewCell.h"
#import "MoviePhotoTableViewCell.h"
#import "MoviePeopleTableViewCell.h"
#import "MovieAllViewController.h"
#import "MovieBuyViewController.h"
#import "UserViewController.h"
#import "CommentViewController.h"
#import "MovieScoreViewController.h"
@interface MovieDetailViewController ()<UITableViewDataSource,UITableViewDelegate,UIScrollViewDelegate>
@property (nonatomic,strong)UITableView *tableView;
@property (nonatomic,strong)MovieDetailModel *detailModel;
@property (nonatomic,strong)MovieStoryModel *storyModel;
@property (nonatomic,strong)NSMutableArray *commentArray;
@property (nonatomic,strong)UILabel *section2Label;
@property (nonatomic,assign)NSInteger section2Index;
@property (nonatomic,assign)CGFloat stop;
@property (nonatomic,strong)NSString *lastId;
@property (nonatomic,strong)NSNumber *storyCount;
@property (nonatomic,strong)AVPlayer *moviePlayer;
@property (nonatomic,strong)UIView *headView;
@property (nonatomic,strong)UIButton *deletButton;
@property (nonatomic,strong)UIButton *playButton;
@property (nonatomic,strong)UISlider *playSlider;
@property (nonatomic,strong)UIView *picture;
@property (nonatomic,assign)BOOL isplay;
@property (nonatomic,strong)NSTimer *timer;
@property (nonatomic,assign)BOOL isselect;
@property (nonatomic,strong)UITapGestureRecognizer *cellTap;
@property (nonatomic,assign)BOOL musicIsPlay;

@end

@implementation MovieDetailViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.

//    self.automaticallyAdjustsScrollViewInsets = NO;
    self.section2Index = 0;
    self.navigationController.navigationBar.hidden = NO;
    self.navigationController.navigationBar.translucent = NO;
    self.navigationItem.title = _movieMainModel.title;

    
    self.tableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 0, kWidth, kHeight-64) style:UITableViewStyleGrouped];
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    [self.view addSubview:_tableView];
    
    self.detailModel = [[MovieDetailModel alloc]init];
    self.storyModel = [[MovieStoryModel alloc]init];
    self.commentArray = [NSMutableArray array];
    [self.tableView registerNib:[UINib nibWithNibName:@"MovieStoryTableViewCell" bundle:nil] forCellReuseIdentifier:@"storyTableViewCell"];
    [self.tableView registerNib:[UINib nibWithNibName:@"MovieTableTableViewCell" bundle:nil] forCellReuseIdentifier:@"tableTableViewCell"];
    [self.tableView registerNib:[UINib nibWithNibName:@"MovieCommentTableViewCell" bundle:nil] forCellReuseIdentifier:@"commentTableViewCell"];
    [self.tableView registerNib:[UINib nibWithNibName:@"MoviePhotoTableViewCell" bundle:nil] forCellReuseIdentifier:@"photoTableViewCell"];
    [self.tableView registerNib:[UINib nibWithNibName:@"MoviePeopleTableViewCell" bundle:nil] forCellReuseIdentifier:@"peopleTableViewCell"];
    
    [self netRequest];
    self.tableView.rowHeight = UITableViewAutomaticDimension;
    self.tableView.estimatedRowHeight = 2;
    self.tableView.allowsSelection = NO;
    

    
    // 上拉刷新
    self.tableView.mj_footer = [MJRefreshAutoFooter footerWithRefreshingBlock:^{
        if (self.commentArray.count == 0) {
            self.lastId = @"0";
        }else{
            MovieCommentModel *model = self.commentArray[self.commentArray.count-1];
            self.lastId = model.MyId;
        }
        [self commentNrtRequest];
    }];
    
    [self headVideo];

}

- (void)headVideo{
    self.moviePlayer = [[AVPlayer alloc]init];
    self.headView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, kWidth, 200)];
    self.headView.backgroundColor = [UIColor blackColor];
    [self.view addSubview:_headView];
    self.headView.hidden = YES;
    
    UITapGestureRecognizer *videoTap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(videoTapAction:)];
    [self.headView addGestureRecognizer:videoTap];
    self.headView.userInteractionEnabled = YES;
    
    self.deletButton = [UIButton buttonWithType:UIButtonTypeCustom];
    self.deletButton.frame = CGRectMake(kWidth-30, 10, 20, 20);
    [self.deletButton setImage:[UIImage imageNamed:@"取消.png"] forState:UIControlStateNormal];
    [self.deletButton addTarget:self action:@selector(deletButtonAction:) forControlEvents:UIControlEventTouchUpInside];
    [self.headView addSubview:_deletButton];
    
    self.playButton = [UIButton buttonWithType:UIButtonTypeCustom];
    self.playButton.frame = CGRectMake(20, 200-32, 25, 25);
    [self.playButton setImage:[UIImage imageNamed:@"暂停.png"] forState:UIControlStateNormal];
    [self.playButton addTarget:self action:@selector(playButtonAction:) forControlEvents:UIControlEventTouchUpInside];
    [self.headView addSubview:_playButton];
    
    self.playSlider = [[UISlider alloc]initWithFrame:CGRectMake(50, 200-30, kWidth-80, 20)];
    [self.headView addSubview:_playSlider];
    [self.playSlider setThumbImage:[UIImage imageNamed:@"小圆.png"] forState:UIControlStateNormal];
    self.playSlider.minimumTrackTintColor = [UIColor whiteColor];
    [self.playSlider addTarget:self action:@selector(playSliderAction:) forControlEvents:UIControlEventTouchUpInside];
    self.playSlider.value = 0;
    self.isplay = YES;
    
    self.timer = [NSTimer scheduledTimerWithTimeInterval:0.5 target:self selector:@selector(timerAction:) userInfo:nil repeats:YES];
    [self.timer fire];
    
}
- (void)netRequest{
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    // 电影详情
    [manager GET:[NSString stringWithFormat:@"http://v3.wufazhuce.com:8000/api/movie/detail/%@",self.movieMainModel.myId] parameters:nil progress:^(NSProgress * _Nonnull downloadProgress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSDictionary *dataDic = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers error:nil];
        NSDictionary *dic = dataDic[@"data"];
        [self.detailModel setValuesForKeysWithDictionary:dic];
        MovieHeadView *movieHeadView = [[UINib nibWithNibName:@"MovieHeadView" bundle:nil] instantiateWithOwner:self options:nil].firstObject;
        [movieHeadView.buyButton addTarget:self action:@selector(buyAction:) forControlEvents:UIControlEventTouchUpInside];
        [movieHeadView.picImageView sd_setImageWithURL:[NSURL URLWithString:self.detailModel.detailcover]];
        self.tableView.tableHeaderView = movieHeadView;
        dispatch_async(dispatch_get_main_queue(), ^{
            [self.tableView reloadData];
            
        });
        movieHeadView.picImageView.userInteractionEnabled = YES;
        UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(tapAction:)];
        [movieHeadView.picImageView addGestureRecognizer:tap];
        [movieHeadView.shareButton addTarget:self action:@selector(shareButtonAction:) forControlEvents:UIControlEventTouchUpInside];
        [movieHeadView.writeButton addTarget:self action:@selector(whiteButtonAction:) forControlEvents:UIControlEventTouchUpInside];
       
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        
    }];
    // 电影故事
    [manager GET:[NSString stringWithFormat:@"http://v3.wufazhuce.com:8000/api/movie/%@/story/1/0",self.movieMainModel.myId] parameters:nil progress:^(NSProgress * _Nonnull downloadProgress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSDictionary *dataDic = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers error:nil];
        NSDictionary *dic = dataDic[@"data"];
        self.storyCount = dic[@"count"];
        NSArray *dataArray = dic[@"data"];
        [self.storyModel setValuesForKeysWithDictionary:dataArray.firstObject];
        dispatch_async(dispatch_get_main_queue(), ^{
            [self.tableView reloadData];
        });
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        
    }];
    // 评论
    [manager GET:[NSString stringWithFormat:@"http://v3.wufazhuce.com:8000/api/comment/praiseandtime/movie/%@/0",self.movieMainModel.myId] parameters:nil progress:^(NSProgress * _Nonnull downloadProgress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSDictionary *dataDic = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers error:nil];
        NSDictionary *datadic = dataDic[@"data"];
        NSArray *dataArray = datadic[@"data"];
        for (NSDictionary *dic in dataArray) {
            MovieCommentModel *model = [[MovieCommentModel alloc]init];
            [model setValuesForKeysWithDictionary:dic];
            [self.commentArray addObject:model];
        }
        dispatch_async(dispatch_get_main_queue(), ^{
            [self.tableView reloadData];
        });
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        
    }];
    
}
- (void)whiteButtonAction:(UIButton *)sender{
    MovieScoreViewController *scoreVC = [[MovieScoreViewController alloc]init];
    [self.navigationController pushViewController:scoreVC animated:YES];
}
- (void)shareButtonAction:(UIButton *)sender{
    NSArray *imageArray = @[self.detailModel.detailcover];
    // （注意：图片必须要在Xcode左边目录里面，名称必须要传正确，如果要分享网络图片，可以这样传iamge参数 images:@[@"http://mob.com/Assets/images/logo.png?v=20150320"]）
    if (imageArray) {
        
        NSMutableDictionary *shareParams = [NSMutableDictionary dictionary];
        [shareParams SSDKSetupShareParamsByText:self.detailModel.officialstory
                                         images:imageArray
                                            url:[NSURL URLWithString:self.detailModel.web_url]
                                          title:self.detailModel.title
                                           type:SSDKContentTypeAuto];
        //2、分享（可以弹出我们的分享菜单和编辑界面）//要显示菜单的视图, iPad版中此参数作为弹出菜单的参照视图，只有传这个才可以弹出我们的分享菜单，可以传分享的按钮对象或者自己创建小的view 对象，iPhone可以传nil不会影响
        
        [ShareSDK showShareActionSheet:nil
         
                                 items:nil
                           shareParams:shareParams
                   onShareStateChanged:^(SSDKResponseState state, SSDKPlatformType platformType, NSDictionary *userData, SSDKContentEntity *contentEntity, NSError *error, BOOL end) {
                       
                       switch (state) {
                           case SSDKResponseStateSuccess:
                           {
                               [self alert:@"分享成功"];
                               break;
                           }
                           case SSDKResponseStateFail:
                           {
                               [self alert:@"分享失败"];
                               break;
                           }
                           default:
                               break;
                       }
                   }
         ];}
}

- (void)alert:(NSString *)string{
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:nil message:string preferredStyle:UIAlertControllerStyleAlert];
    [self presentViewController:alert animated:YES completion:nil];
    UIAlertAction *cancel = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleCancel handler:nil];
    [alert addAction:cancel];
}
- (void)commentNrtRequest{
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    // 评论
    [manager GET:[NSString stringWithFormat:@"http://v3.wufazhuce.com:8000/api/comment/praiseandtime/movie/%@/%@",self.movieMainModel.myId,self.lastId] parameters:nil progress:^(NSProgress * _Nonnull downloadProgress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSDictionary *dataDic = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers error:nil];
        NSDictionary *datadic = dataDic[@"data"];
        NSArray *dataArray = datadic[@"data"];
        
        for (NSDictionary *dic in dataArray) {
            MovieCommentModel *model = [[MovieCommentModel alloc]init];
            [model setValuesForKeysWithDictionary:dic];
            [self.commentArray addObject:model];
        }
        dispatch_async(dispatch_get_main_queue(), ^{
            [self.tableView reloadData];
            [self performSelector:@selector(endendend) withObject:self afterDelay:1];
        });
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        
    }];
}
- (void)endendend {
    [self.tableView.mj_footer endRefreshing];
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 3;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    if (section == 0) {
        return 1;
    }else if (section == 1){
        return 1;
    }else{
        return self.commentArray.count;
    }
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.section == 0) {
        MovieStoryTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"storyTableViewCell" forIndexPath:indexPath];
        NSString *username = [self.storyModel.user objectForKey:@"user_name"];
        NSString *weburl = [self.storyModel.user objectForKey:@"web_url"];
        [cell.picImageView sd_setImageWithURL:[NSURL URLWithString:weburl]];
        cell.picImageView.layer.cornerRadius = 55/2;
        cell.picImageView.layer.masksToBounds = YES;
        cell.authorLabel.text = username;
        cell.dateLabel.text = [self.storyModel.input_date substringToIndex:10];
        cell.titleLabel.text = self.storyModel.title;
        cell.countLabel.text = [NSString stringWithFormat:@"%@",self.storyModel.praisenum];
        cell.contentLabel.text = self.storyModel.content;
        cell.scoreLabel.text = @"";
        cell.picImageView.userInteractionEnabled = YES;
        UITapGestureRecognizer *Tap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(cellTapAction:)];
        [cell.picImageView addGestureRecognizer:Tap];
        
        
        return cell;
    }else if(indexPath.section == 1){
        if (self.section2Index == 0) {
            self.section2Label.text = @"一个电影表";
            MovieTableTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"tableTableViewCell" forIndexPath:indexPath];
            NSMutableArray *array = [self aaa:self.detailModel.keywords];
            if (array.count == 5) {
                cell.label1.text = array[0];
                cell.label2.text = array[1];
                cell.label3.text = array[2];
                cell.label4.text = array[3];
                cell.label5.text = array[4];
            }
            
            return cell;
        }else if (self.section2Index == 1){
            self.section2Label.text = @"剧照";
            MoviePhotoTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"photoTableViewCell" forIndexPath:indexPath];
            NSArray *photoArray = self.detailModel.photo;
            [cell scrollViewWithArray:photoArray];
            
            return cell;
        }else{
            self.section2Label.text = @"演职人员";
            MoviePeopleTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"peopleTableViewCell" forIndexPath:indexPath];
            cell.peopleLabel.text = self.detailModel.info;
            
            return cell;
        }
      
    }else{
//        MovieCommentTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"commentTableViewCell" forIndexPath:indexPath];
        MovieStoryTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"storyTableViewCell" forIndexPath:indexPath];
        MovieCommentModel *model = self.commentArray[indexPath.row];
        NSString *username = [model.user objectForKey:@"user_name"];
        NSString *weburl = [model.user objectForKey:@"web_url"];
        [cell.picImageView sd_setImageWithURL:[NSURL URLWithString:weburl]];
        cell.picImageView.layer.cornerRadius = 55/2;
        cell.picImageView.layer.masksToBounds = YES;
        cell.authorLabel.text = username;
        cell.dateLabel.text = [model.input_date substringToIndex:10];
        cell.countLabel.text = [NSString stringWithFormat:@"%@",model.praisenum];
        cell.contentLabel.text = model.content;
        cell.titleLabel.text = @"";
        cell.scoreLabel.text = model.score;
        cell.picImageView.userInteractionEnabled = YES;
        self.cellTap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(cellTapAction1:)];
        [cell.picImageView addGestureRecognizer:_cellTap];
        
        return cell;
    }
    
}
- (void)cellTapAction1:(UITapGestureRecognizer *)tap{
    MovieStoryTableViewCell *cell = (MovieStoryTableViewCell *)tap.view.superview.superview;
    NSIndexPath *indexPath = [self.tableView indexPathForCell:cell];
    MovieCommentModel *model = self.commentArray[indexPath.row];
    UserViewController *user = [[UserViewController alloc]init];
    user.modelID = model.user[@"user_id"];
    [self.navigationController pushViewController:user animated:YES];
    
}
- (void)cellTapAction:(UITapGestureRecognizer *)tap{
    UserViewController *user = [[UserViewController alloc]init];
    user.modelID = _storyModel.user[@"user_id"];
    [self.navigationController pushViewController:user animated:YES];
    
}
- (NSMutableArray *)aaa:(NSString *)str{
    NSMutableArray *array =[NSMutableArray array];
    NSString *str1 = @"";
    for (NSInteger i = 0; i<str.length; i++) {
        NSString *string = [str substringWithRange:NSMakeRange(i, 1)];
        if ([string isEqualToString:@";"]) {
            [array addObject:str1];
            str1 = @"";
        }else{
            str1 = [str1 stringByAppendingString:string];
        }
    }
    [array addObject:str1];
    return array;
}
// 表头高度
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return 30;
}
// 表尾高度
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    if (section == 0) {
        return 30;
    }else{
        return 0;
    }
    
}
// 自定义表头
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    if (section == 0) {
        UIView *oneView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, kWidth, 30)];
        UILabel *label = [[UILabel alloc]initWithFrame:CGRectMake(20, 5, 70, 20)];
        label.text = @"电影故事";
        [oneView addSubview:label];
        UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
        button.frame = CGRectMake(kWidth-10-40, 5, 20, 20);
        [button setBackgroundImage:[UIImage imageNamed:@"拜访小记.png"] forState:UIControlStateNormal];
        [button addTarget:self action:@selector(oneHeadViewButton:) forControlEvents:UIControlEventTouchUpInside];
        [oneView addSubview:button];
        return oneView;
    }
    else if (section == 1){
        UIView *twoView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, kWidth, 30)];
        self.section2Label = [[UILabel alloc]initWithFrame:CGRectMake(20, 5, 100, 20)];
        _section2Label.text = @"一个电影表";
        [twoView addSubview:_section2Label];
        UIButton *button1 = [UIButton buttonWithType:UIButtonTypeCustom];
        button1.frame = CGRectMake(kWidth-200, 5, 20, 20);
        [button1 setBackgroundImage:[UIImage imageNamed:@"电影表.png"] forState:UIControlStateNormal];
        [button1 addTarget:self action:@selector(button1Action:) forControlEvents:UIControlEventTouchUpInside];
        [twoView addSubview:button1];
        
        UIButton *button2 = [UIButton buttonWithType:UIButtonTypeCustom];
        button2.frame = CGRectMake(kWidth-130, 5, 20, 20);
        [button2 setBackgroundImage:[UIImage imageNamed:@"照片.png"] forState:UIControlStateNormal];
        [button2 addTarget:self action:@selector(button2Action:) forControlEvents:UIControlEventTouchUpInside];
        [twoView addSubview:button2];
        
        UIButton *button3 = [UIButton buttonWithType:UIButtonTypeCustom];
        button3.frame = CGRectMake(kWidth-60, 5, 20, 20);
        [button3 setBackgroundImage:[UIImage imageNamed:@"人员介绍.png"] forState:UIControlStateNormal];
        [button3 addTarget:self action:@selector(button3Action:) forControlEvents:UIControlEventTouchUpInside];
        [twoView addSubview:button3];
        
        return twoView;
        
    }else{
        UIView *threeView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, kWidth, 30)];
        UILabel *label = [[UILabel alloc]initWithFrame:CGRectMake(20, 5, 70, 20)];
        label.text = @"评论列表";
        [threeView addSubview:label];
        UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
        button.frame = CGRectMake(kWidth-10-40, 5, 20, 20);
        [button setBackgroundImage:[UIImage imageNamed:@"拜访小记.png"] forState:UIControlStateNormal];
        [button addTarget:self action:@selector(threeHeadViewButton:) forControlEvents:UIControlEventTouchUpInside];
        [threeView addSubview:button];
        return threeView;
    }

}
// 自定义表尾
- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section{
    if (section == 0) {
        UIView *oneView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, kWidth, 30)];
        UILabel *label = [[UILabel alloc]initWithFrame:CGRectMake(20, 5, 150, 20)];
        label.text = [NSString stringWithFormat:@"共%@个故事",self.storyCount];
        label.font = [UIFont systemFontOfSize:15];
        label.textColor = [UIColor grayColor];
        [oneView addSubview:label];
        UIButton *button = [UIButton buttonWithType:UIButtonTypeSystem];
        button.frame = CGRectMake(kWidth-110, 5, 100, 20);
        [button setTitle:@"全部电影故事" forState:UIControlStateNormal];
        [button addTarget:self action:@selector(oneFootViewButton:) forControlEvents:UIControlEventTouchUpInside];
        [oneView addSubview:button];
        return oneView;
    }else{
        return nil;
    }
}
// 第一个表头按钮
- (void)oneHeadViewButton:(UIButton *)sender{
    
    
}
// 第一个表尾按钮
- (void)oneFootViewButton:(UIButton *)sender{
    
    MovieAllViewController *movieAllVC = [[MovieAllViewController alloc]init];
    movieAllVC.movie_id = self.storyModel.movie_id;
    movieAllVC.title = self.movieMainModel.title;
    [self.navigationController pushViewController:movieAllVC animated:YES];
}
// 第二个表头的三个按钮
- (void)button1Action:(UIButton *)sender{
    self.section2Label.text = @"一个电影表";
    self.section2Index = 0;
    [self.tableView reloadData];
//    [self.tableView reloadSections:[NSIndexSet indexSetWithIndex:0] withRowAnimation:UITableViewRowAnimationNone];
    
}
- (void)button2Action:(UIButton *)sender{
    self.section2Label.text = @"剧照";
    self.section2Index = 1;
    [self.tableView reloadData];
//    [self.tableView reloadSections:[NSIndexSet indexSetWithIndex:0] withRowAnimation:UITableViewRowAnimationNone];
    
}
- (void)button3Action:(UIButton *)sender{
    self.section2Label.text = @"演职人员";
    self.section2Index = 2;
    [self.tableView reloadData];
//    [self.tableView reloadSections:[NSIndexSet indexSetWithIndex:0] withRowAnimation:UITableViewRowAnimationNone];
    
}
// 第三个表头的按钮
- (void)threeHeadViewButton:(UIButton *)sender{
    CommentViewController *comment = [[CommentViewController alloc]init];
    [self.navigationController pushViewController:comment animated:YES];
}
- (void)tapAction:(UITapGestureRecognizer *)tap{
    
    _musicIsPlay = [MusicPlayerManager shareInstance].isPlay;
    if (_musicIsPlay) {
        [[MusicPlayerManager shareInstance].player pause];
    }
    self.headView.hidden = NO;
    self.picture = (UIImageView *)tap.view;
    self.picture.hidden = YES;
    [self.tableView setContentOffset:CGPointMake(0, -20) animated:YES];
    AVPlayerLayer *playerlayer = [AVPlayerLayer playerLayerWithPlayer:self.moviePlayer];
    playerlayer.frame = CGRectMake(0, 0, kWidth, 200);
    playerlayer.videoGravity = AVLayerVideoGravityResize;
    
    [self.headView.layer addSublayer:playerlayer];
    [self.headView.layer addSublayer:self.deletButton.layer];
    [self.headView.layer addSublayer:self.playButton.layer];
    [self.headView.layer addSublayer:self.playSlider.layer];

    AVPlayerItem *item = [[AVPlayerItem alloc]initWithURL:[NSURL URLWithString:self.detailModel.video]];
    [self.moviePlayer replaceCurrentItemWithPlayerItem:item];
    [self.moviePlayer play];
    self.isplay = YES;
    if (self.isplay == YES) {
        [self.playButton setImage:[UIImage imageNamed:@"暂停.png"] forState:UIControlStateNormal];
        [self.moviePlayer play];
    }else{
        [self.playButton setImage:[UIImage imageNamed:@"播放.png"] forState:UIControlStateNormal];
        [self.moviePlayer pause];
    }
    [self performSelector:@selector(hide) withObject:self afterDelay:5];

    
}

- (void)hide{
    self.deletButton.hidden = YES;
    self.playButton.hidden = YES;
    self.playSlider.hidden = YES;
    self.isselect = YES;
}
- (void)deletButtonAction:(UIButton *)sender{
    if (_musicIsPlay) {
        [[MusicPlayerManager shareInstance].player play];
    }
    self.headView.hidden = YES;
    self.picture.hidden = NO;
    [self.moviePlayer pause];
    [self.tableView setContentOffset:CGPointMake(0, 0) animated:YES];
}
- (void)playButtonAction:(UIButton *)sender{
    if (self.isplay == YES) {
        [self.playButton setImage:[UIImage imageNamed:@"播放.png"] forState:UIControlStateNormal];
        [self.moviePlayer pause];
        self.isplay = NO;
    }else{
        [self.playButton setImage:[UIImage imageNamed:@"暂停.png"] forState:UIControlStateNormal];
        [self.moviePlayer play];
        self.isplay = YES;
    }
}
- (void)playSliderAction:(UISlider *)sender{
    [self.moviePlayer seekToTime:CMTimeMakeWithSeconds(sender.value, 1) completionHandler:^(BOOL finished) {
        [self.moviePlayer play];
        self.isplay = YES;
    }];
}
- (void)timerAction:(NSTimer *)timer{
    if (self.moviePlayer.currentItem.duration.timescale == 0 || self.moviePlayer.currentTime.timescale == 0) {
        return;
    }
    long long int currentTime = self.moviePlayer.currentTime.value/self.moviePlayer.currentTime.timescale;
    long long int allTime = self.moviePlayer.currentItem.duration.value/self.moviePlayer.currentItem.duration.timescale;
    
    self.playSlider.maximumValue = allTime;
    self.playSlider.value = currentTime;

}
- (void)videoTapAction:(UITapGestureRecognizer *)videoTap{

    if (self.isselect == YES) {
        self.playButton.hidden = NO;
        self.playSlider.hidden = NO;
        self.deletButton.hidden = NO;
        self.isselect =! self.isselect;
        [self performSelector:@selector(hide) withObject:self afterDelay:5];

    }else {
        self.playButton.hidden = YES;
        self.playSlider.hidden = YES;
        self.deletButton.hidden = YES;
        self.isselect =! self.isselect;
    }
}
- (void)scrollViewDidScroll:(UIScrollView *)scrollView{

}
- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    self.tabBarController.tabBar.hidden = YES;
    self.navigationController.navigationBar.hidden = NO;
    self.navigationController.navigationBarHidden = NO;
}
- (void)viewDidAppear:(BOOL)animated{
    [super viewDidAppear:animated];
    self.tabBarController.tabBar.hidden = YES;
}
- (void)searchButtonAction:(UIButton *)sender{
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)buyAction:(UIButton *)sender{
    MovieBuyViewController *buy = [[MovieBuyViewController alloc]init];
    buy.movie_id = _detailModel.movie_id;
    [self.navigationController pushViewController:buy animated:YES];
}
- (void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
    [self.moviePlayer pause];
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
